package com.tripcube.file.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.OSSErrorCode;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.tripcube.file.config.AliyunOssConfig;
import com.tripcube.file.service.ISysFileService;
import com.tripcube.file.utils.FileUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

/**
 * 阿里云OSS文件存储服务
 */
@Service
public class AliyunOssSysFileServiceImpl implements ISysFileService {

    @Autowired
    private AliyunOssConfig aliyunOssConfig;

    @Autowired
    private OSS ossClient;

    /**
     * 阿里云OSS文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     */
    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        InputStream inputStream = null;
        try {
            String fileName = FileUploadUtils.extractFilename(file);
            inputStream = file.getInputStream();

            // 创建PutObject请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    aliyunOssConfig.getBucketName(),
                    fileName,
                    inputStream);

            // 上传文件
            ossClient.putObject(putObjectRequest);

            // 生成文件访问URL
            return generateFileUrl(fileName);
        } catch (OSSException oe) {
            throw new RuntimeException("阿里云OSS上传文件失败: " + oe.getMessage());
        } catch (Exception e) {
            throw new RuntimeException("阿里云OSS上传文件异常", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    // 静默关闭
                }
            }
        }
    }

    /**
     * 阿里云OSS文件删除接口
     *
     * @param fileUrl 文件访问URL
     */
    @Override
    public void deleteFile(String fileUrl) throws Exception {
        try {
            // 从URL中提取文件名
            String fileName = extractFileNameFromUrl(fileUrl);

            // 创建删除请求
            DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(aliyunOssConfig.getBucketName());
            deleteObjectsRequest.setKeys(List.of(fileName));

            // 删除文件
            ossClient.deleteObjects(deleteObjectsRequest);
        } catch (OSSException oe) {
            if (!OSSErrorCode.NO_SUCH_KEY.equals(oe.getErrorCode())) {
                throw new RuntimeException("阿里云OSS删除文件失败: " + oe.getMessage());
            }
        } catch (Exception e) {
            throw new RuntimeException("阿里云OSS删除文件异常", e);
        }
    }

    /**
     * 生成文件访问URL
     *
     * @param fileName 文件名
     * @return 访问URL
     */
    private String generateFileUrl(String fileName) {
        // 返回文件访问URL（公开访问URL）
        return "https://" + aliyunOssConfig.getBucketName() + "." + aliyunOssConfig.getEndpoint() + "/" + fileName;
    }

    /**
     * 从URL中提取文件名
     *
     * @param fileUrl 文件URL
     * @return 文件名
     */
    private String extractFileNameFromUrl(String fileUrl) {
        // 从URL中提取文件名
        int lastSlashIndex = fileUrl.lastIndexOf('/');
        if (lastSlashIndex != -1 && lastSlashIndex < fileUrl.length() - 1) {
            return fileUrl.substring(lastSlashIndex + 1);
        }
        return fileUrl;
    }
}
